package com.wq.nio.file;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: wangqiang20995
 * @Date:2018/8/22
 * @Description:
 * @Resource:
 */
public class FileChannelDemo {

    public static void main(String args[]) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\Program Files\\IdeaProjects\\JavaKnowledge\\nio\\src\\main\\resources\\hello.txt", "r");
        FileChannel fileChannel = randomAccessFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        System.out.println("before read capacity --> " + buffer.capacity());
        int readByte = fileChannel.read(buffer);
        System.out.println("after read capacity --> " + buffer.capacity());
        while (readByte != -1) {//没有读到文件末尾
            System.out.println("read length --> " + readByte);

            System.out.println("limit before flip --> " + buffer.limit());
            buffer.flip();//切换模式，write-->read/read-->write
            System.out.println("limit after flip --> " + buffer.limit());

//            while (buffer.hasRemaining()) {
                readData(buffer);
//            }

            buffer.capacity();
            System.out.println("\nlimit after capacity --> " + buffer.limit());

            System.out.println("-------------------write char-------------------");
            buffer = writeDate(buffer,'a');

            System.out.println("----------------------------------");
            buffer.rewind();//重新读一遍，把position置为0，limit=writeMaxIndex，capacity=size

            while (buffer.hasRemaining()) {
                byte data = buffer.get();
                System.out.print((char) data);
            }

            buffer.clear();
            readByte = fileChannel.read(buffer);
        }

        fileChannel.close();

    }

    private static void readData(ByteBuffer buffer) {
//        System.out.println("position before read --> " + buffer.position());
        byte data = buffer.get();
//        System.out.println("position after read --> " + buffer.position());
//        System.out.println(data + "-" + (char) data);
                System.out.print((char) data);
    }

    private static ByteBuffer writeDate(ByteBuffer buffer,char code){
        ByteBuffer allocate = ByteBuffer.allocate(buffer.limit() + 1);
        allocate.put((byte) 98);
        allocate.put(buffer);
        allocate.put(allocate.capacity() - 1,(byte)code);//index=[0,allocate.size-1]

        return allocate;
    }
}
